﻿using System;
using NHibernate.Event;
using Hippo.Core.Model;

namespace Hippo.Core.Data
{
    public class AuditEventListener : IPreInsertEventListener, IPreUpdateEventListener
    {
        public bool OnPreInsert(PreInsertEvent @event)
        {
            if (@event.Entity is IAuditableModel)
            {
                IAuditableModel auditableModel = @event.Entity as IAuditableModel;
                auditableModel.CreatedTime = DateTime.Now;
                auditableModel.CreatedBy = System.Threading.Thread.CurrentPrincipal.Identity.Name;
                auditableModel.UpdatedTime = auditableModel.CreatedTime;
                auditableModel.UpdatedBy = auditableModel.CreatedBy;
            }
            return true;
        }

        public bool OnPreUpdate(PreUpdateEvent @event)
        {
            if (@event.Entity is IAuditableModel)
            {
                IAuditableModel auditableModel = @event.Entity as IAuditableModel;
                auditableModel.UpdatedTime = DateTime.Now;
                auditableModel.UpdatedBy = System.Threading.Thread.CurrentPrincipal.Identity.Name;
            }
            return true;
        }
    }
}
